package org.databasefacade.translator;

import org.databasefacade.select.Comparison;
import org.databasefacade.select.From;
import org.databasefacade.select.Join;
import org.databasefacade.select.Where;
import org.databasefacade.table.Table;
import org.databasefacade.update.Update;

public class DefaultAnsiUpdate {

	public static String getUpdateAnsiSQL(Update update, From rawFrom, Where where) {
		From from = rawFrom.prepareForAnsiUpdate(where);
		StringBuilder sb = new StringBuilder("");
		String ansiSqlSubSelect = "";
		if ( from.getFromTable() != null ) {
			ansiSqlSubSelect = generateAnsiSqlSubSelect(from, where);
		}
		sb.append(update.getSQL(ansiSqlSubSelect));
		sb.append(genarateUpdateTableWhere(update.getUpdateTable(), where));
		return sb.toString();
	}
	
	private static String generateAnsiSqlSubSelect(From from, Where where) {
		String from_plus_where = from.getSQL() + where.getSQL();
		Translator translator = from.getTranslator();
		if ( translator.getJoinNotationMode() == Join.NATIVE_NOTATION ) {
			from_plus_where = translator.buildNativeFromSQL(from, where);
			from_plus_where += "\n  " + translator.buildNativeWhereSQL(from, where);
		} 
		return from_plus_where;
	}
	
	/**
	 * The where should match the original hierarchy of conditions but
	 * only for the update table.
	 */
	private static String genarateUpdateTableWhere(Table table, Where where) {
		Where updateWhere = new Where();
		Comparison comp = where.getWhereCompare();
		if ( comp.isRestrictedToTable(table) ) {
			updateWhere.first(comp);
		} else {
			Comparison dummy = new Comparison();
			dummy.alwaysTrue();
			updateWhere.first(dummy);
		}
		updateWhere.conditions().and(where.conditions().buildExclusiveForTable(table));
		return updateWhere.getSQL();		
	}
}
